﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Eneta.Portal.Common.Dto;
using Eneta.Portal.Common.Repository;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Eneta.Portal.Common;

namespace Eneta.Portal.NewsAndBlogs.Controls
{
    public class BlogDetailViewControl : UserControl
    {
        protected HtmlAnchor profilePhotoLink;
        protected HtmlImage profilePhoto;
        protected HtmlAnchor blogTitleField;
        protected HtmlAnchor authorField;
        protected HtmlAnchor blogUrlField;
        protected HtmlAnchor rssUrlField;
        protected HtmlGenericControl blogDescriptionField;
        protected HtmlGenericControl blogFirstPostDate;

        protected HtmlGenericControl firstPostContainer;
        protected HtmlAnchor firstPostProfileLink;
        protected HtmlImage firstPostProfileImage;
        protected HtmlAnchor firstPostTitle;
        protected HtmlAnchor firstPostAuthorLink;
        protected HtmlAnchor firstPostBlogLink;
        protected HtmlGenericControl firstPostDate;
        protected HtmlGenericControl firstPostSummary;
        protected HtmlAnchor firstPostReadMore;
        protected HtmlAnchor firstPostCommentsCountLink;

        protected Repeater firstPostTagsRepeater;
        protected Repeater newPostsRepeater;
        protected Repeater olderPostsRepeater;

        protected HtmlAnchor footerBlogLink;
        protected HtmlImage footerProfileImage;
        protected HtmlGenericControl footerBlogName;

        protected HtmlAnchor prevLink;
        protected HtmlAnchor nextLink;
        protected HtmlGenericControl pagerBottomPrevContainer;
        protected HtmlGenericControl pagerBottomNextContainer;

        private BlogDto _blog;
        private UserProfileDto _ownerProfile;

        private UserProfileDto OwnerProfile
        {
            get
            {
                if (_ownerProfile != null)
                    return _ownerProfile;

                var repository = new UserProfileRepository(SPContext.Current.Web);
                _ownerProfile = repository.GetUserProfileById(Blog.OwnerProfileId);
                return _ownerProfile;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (SPContext.Current.FormContext != null)
                if (SPContext.Current.FormContext.FormMode == SPControlMode.Edit)
                    return;

            if (Blog == null)
            {
                var user = SPContext.Current.Web.CurrentUser;
                if (user != null)
                    if (user.IsSiteAdmin)
                        return;

                Response.Redirect(EnetaApplication.PortalBlogSiteUrl);
                return;
            }

            Bind();
        }

        private void Bind()
        {
            profilePhotoLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + Blog.OwnerProfileId;
            profilePhoto.Src = OwnerProfile.UserImage64x64Url;

            authorField.HRef = profilePhotoLink.HRef;
            authorField.InnerText = Blog.OwnerName;

            rssUrlField.HRef = Blog.RssUrl;

            blogTitleField.InnerText = Blog.Title;
            blogTitleField.HRef = Blog.Url;

            blogFirstPostDate.InnerText = GetResourceString("FirstPostLabel") + " " + Blog.FirstEntryDate.ToShortDateString();

            blogUrlField.InnerText = Blog.Url;
            blogUrlField.HRef = Blog.Url;

            // TODO: Loe korrektne RSS 
            rssUrlField.HRef = Blog.RssUrl;
            blogDescriptionField.InnerText = Blog.Description;

            footerBlogLink.HRef = Blog.DisplayUrl;
            footerBlogName.InnerText = Blog.Title;
            footerProfileImage.Src = profilePhoto.Src;

            BindEntries();
        }

        protected void BindEntries()
        {
            var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
            var pageString = Request.QueryString["page"];
            var page = 0;
            if (!int.TryParse(pageString, out page))
                page = 1;
            if (page <= 0)
                page = 1;
            var pageSize = 15;

            var posts = repository.GetApprovedEntriesByBlog(Blog.ID, page, pageSize);
            if (posts == null)
            {
                firstPostContainer.Visible = false;
                return;
            }
            if (posts.Results.Count == 0)
            {
                firstPostContainer.Visible = false;
                firstPostContainer.Visible = false;
            }
            else
            {
                firstPostContainer.Visible = true;


                BindFirstPost(posts.Results[0]);
                BindNewPosts(posts.Results);
                BindOlderPosts(posts.Results);
            }

            if (page == 1 || posts.PageCount <= 1)
                pagerBottomPrevContainer.Visible = false;
            if (posts.PageCount <= 1 || posts.Page >= posts.PageCount-1)
                pagerBottomNextContainer.Visible = false;

            prevLink.HRef = Request.ServerVariables["PATH_INFO"];
            if(page > 2)
                prevLink.HRef+= "?page=" + (page-1);

            nextLink.HRef = Request.ServerVariables["PATH_INFO"] + "?page=" + (page + 1);
        }        

        protected void BindFirstPost(BlogEntryDto firstPost)
        {
            firstPostProfileLink.HRef = EnetaApplication.PortalProfilePageUrl + "?profileID=" + Blog.OwnerProfileId;
            firstPostProfileImage.Src = OwnerProfile.UserImage32x32Url;
            firstPostTitle.InnerText = firstPost.Title;
            firstPostTitle.HRef = firstPost.DisplayUrl;
            firstPostAuthorLink.InnerText = Blog.OwnerName;
            firstPostAuthorLink.HRef = firstPostProfileLink.HRef;
            firstPostBlogLink.InnerText = Blog.Title;
            firstPostBlogLink.HRef = Blog.Url;
            firstPostDate.InnerText = firstPost.Date.ToString(@"dd\.MM\.yyyy");
            firstPostSummary.InnerText = firstPost.Summary;
            firstPostReadMore.HRef = firstPost.DisplayUrl;


            if (firstPost.Comments.Count > 0)
            {
                firstPostCommentsCountLink.HRef = firstPostTitle.HRef + "#comments";
                firstPostCommentsCountLink.InnerHtml = "<span>(" + firstPost.Comments.Count + ")</span>";
            }
            else
                firstPostCommentsCountLink.Visible = false;

            firstPostTagsRepeater.DataSource = firstPost.Keywords;
            firstPostTagsRepeater.DataBind();
        }

        protected void BindNewPosts(IList<BlogEntryDto> posts)
        {
            var newPosts = posts.Skip(1).Take(4);
            newPostsRepeater.DataSource = newPosts;
            newPostsRepeater.DataBind();
        }

        protected void BindOlderPosts(IList<BlogEntryDto> posts)
        {
            var oldPosts = posts.Skip(5).Take(15);
            olderPostsRepeater.DataSource = oldPosts;
            olderPostsRepeater.DataBind();
        }

        protected BlogDto Blog
        {
            get
            {
                if (_blog != null)
                    return _blog;

                var repository = new BlogRepository(EnetaApplication.PortalBlogSiteUrl);
                var id = SPContext.Current.ItemId;
                _blog = repository.GetBlogById(id);
                return _blog;
            }
        }

        private object GetResourceString(string label)
        {
            var resourceString = "$Resources:NewsAndBlogs," + label;
            var result = SPUtility.GetLocalizedString(resourceString, "NewsAndBlogs", SPContext.Current.Web.Language);
            return result;
        }

    }
}
